package com.lagou.model;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author Kirito
 * @description:
 * @date 2020/04/24
 */
public class RequestBuilder {

    /**
     * 从输入流中获取相关的请求信息，并封装成Request
     *
     * @param inputStream InputStream
     * @return Request
     */
    public Request buildRequest(InputStream inputStream) throws IOException {
        // 网络可能存在数据中断，这里执行循环判断，如果读到的数据长度为0，一直读取
        int length = 0;
        while (length == 0) {
            length = inputStream.available();
        }
        byte[] bytes = new byte[length];
        // 读取数据
        inputStream.read(bytes);
        String data = new String(bytes);

        String[] datas = data.split("\r\n");
        // 解析数据，第一行就是封装了请求method和请求url的相关信息，如：GET / HTTP1.1
        String header = datas[0];
        // 再将请求信息按空格进行分割
        String[] headers = header.split(" ");
        String method = headers[0].trim();
        System.out.println("=======>>>Request method: " + method);
        String url = headers[1].trim();
        System.out.println("=======>>>Request url: " + url);

        String[] hosts = datas[1].split(":");
        String host = hosts[1].split(":")[0].trim();
        return new Request(host, method, url);
    }
}
